<?php

namespace app\api\controller;

use app\admin\model\Activity as ActivityModel;
use app\admin\model\ActivityBgMusicTpl;
use app\admin\model\ActivityBgTpl as ActivityBgTplModel;
use app\admin\model\PrizeRecord;
use app\common\controller\Frontend;
use app\common\model\Answer;
use app\common\model\AnswerSheet;
use app\common\model\AnswerSheetData;
use app\common\model\Custom as CustomModel;
use app\common\model\OrganizeUser as OrganizeUserModel;
use app\common\model\ProgramRecord;
use app\common\model\Questions;
use app\common\model\Share;
use app\common\model\SmsRecord;
use app\common\model\UserScoreRecord;
use Exception;
use jueqi\AliYunSms;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

class Index extends Frontend
{
    protected $noNeedLogin = ['getWeChatShare', 'zdyPage', 'sendCode', 'getXcxConfig'];

    public function initialize()
    {
        parent::initialize();
    }

    public function index()
    {
        $param      = $this->request->param();
        $activityId = $param['activity_id'] ?? 0; // 活动ID
        $source     = getSource();
        $client     = checkMobile();
        if ($this->request->isGet()) {
            if ($source === 'xcx') {
                $xcxConfig = get_sys_config("", 'xcx_config');
                $isSwitch  = $xcxConfig['is_switch'] ?? 0; // 骗审开关
                if ($isSwitch == 1) {
                    $activityId = $xcxConfig['activity_id'] ?? 0;
                }
                if (empty($activityId)) {
                    $this->error("请通过扫小程序码参加活动！");
                }
            }
        }
        if (empty($activityId)) {
            $this->error("活动异常！");
        }

        $customModel = new CustomModel();
        $musicInfo   = array();
        $customInfo  = array();
        $fictitious  = 0;
        try {
            // 查询自定义配置
            $customInfo = $customModel->where("activity_id", $activityId)->find();
            if (!empty($customInfo)) {
                $musicId = $customInfo->music_id ?? 0; // 背景音乐ID
                $onlywx  = $customInfo->onlywx ?? 2;
                if (!empty($musicId)) {
                    $musicInfo = (new ActivityBgMusicTpl)->field("file_url")->find($musicId);
                }
                if ($onlywx == 1 && $source !== 'xcx' && $source !== 'wechat') {
                    $this->error("请通过微信客户端登入！");
                }
            }
            $fictitious = $customInfo->fictitious ?? 0; // 虚拟参与人数
            if (empty($fictitious)) {
                $fictitious = 0;
            }
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
        }

//        if ($closewx == 2 && ($source === 'wechat' || $source === 'xcx')) {
//            $appid        = get_sys_config("appid");
//            $redirect_uri = Route::buildUrl('api/WeChat/auth')->domain(true) . '?activity_id=' . $activityId;
//            $path         = $activityId;
//            $url          = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . $redirect_uri . '&response_type=code&scope=snsapi_userinfo&state=' . $path . '#wechat_redirect';
//            $tokenName       = Config::get("backstage.user_token_name");
//            $serverTokenName = Config::get("backstage.user_server_token_name");
//            $this->auth      = Auth::instance();
//            $token           = $this->request->server($serverTokenName, $this->request->request($tokenName, Cookie::get($tokenName) ?: false));
//            if(empty($token)){
//                $this->error("", ['url' => $url], 302);
//            }
//            try {
//                $this->auth->init($token);
//                if (!$this->auth->isLogin()) {
//                    $this->error("", ['url' => $url], 302);
//                }
//            } catch (HttpResponseException $e) {
//                $exceptionData = $e->getResponse()->getData();
//                $exceptionCode = $exceptionData['code'] ?? 0;
//                if($exceptionCode === 409){
//                    $this->error("", ['url' => $url], 302);
//                }
//            }
//        }
        // 查询活动信息
        $activityModel = new ActivityModel();
        $cdnUrl        = get_cdn_url();
        try {
            $activityInfo = $activityModel
                ->field("id,name,status,synopsis,start_time,end_time,pc_tpl_id,
                android_tpl_id,copyright,images_address")
                ->where("id", $activityId)
                ->find();
            if (empty($activityInfo)) {
                $this->error("活动不存在！");
            }
            $time         = time();
            $status       = $activityInfo->status ?? 0; // 活动状态
            $startTime    = $activityInfo->start_time ?? 0; // 活动开始时间
            $endTime      = $activityInfo->end_time ?? 0; // 活动结束时间
            $pcTplId      = $activityInfo->pc_tpl_id ?? 0; // pc端模板ID
            $androidTplId = $activityInfo->android_tpl_id ?? 0; // 手机端模板ID

            $sheetCount = (new AnswerSheet())->where("activity_id", $activityId)->count();
            if (empty($sheetCount) || !is_numeric($sheetCount)) {
                $sheetCount = 0;
            }
            $total = $sheetCount + $fictitious; // 虚拟参与人数+加实际参数人数
            if (empty($total)) {
                $total = 0;
            }

            $pcBgTpl     = "";
            $mobileBgTpl = "";
            // 查询背景模板
            if (!empty($pcTplId) || !empty($androidTplId)) {
                $bgTplModel = new ActivityBgTplModel();
                if (!empty($pcTplId)) {
                    $bgTplInfo = $bgTplModel->field("img")->find($pcTplId);
                    $pcBgTpl   = $bgTplInfo->img ?? '';
                }
                if (!empty($androidTplId)) {
                    $bgTplInfo   = $bgTplModel->field("img")->find($androidTplId);
                    $mobileBgTpl = $bgTplInfo->img ?? '';
                }
            }
            $activityInfo['pc_bg_tpl']     = $pcBgTpl;
            $activityInfo['mobile_bg_tpl'] = $mobileBgTpl;

            // 查询活动信息
            $questionsModel = new Questions();
            $list           = $questionsModel
                ->alias('q')
                ->with(['answerInfo'])
                ->where(['q.activity_id' => $activityId])
                ->order("xh", 'ASC')
                ->select()
                ->toArray();

            foreach ($list as &$ques) {
                $glType   = $ques['gl_type'] ?? '';
                $glOption = $ques['gl_option'] ?? '';
                if (empty($glOption)) {
                    continue;
                }
                $glOption = json_decode($glOption, true);
                if ($glType === 'or') {
                    foreach ($glOption as $k => $v) {
                        $att[]   = $k;
                        $att[]   = implode(";", explode(",", $v));
                        $arr[$k] = implode(",", $att);
                        $att     = array();
                        $gl      = implode("|", $arr);
                        $arr     = array();
                    }
                } else if ($glType === 'and') {
                    foreach ($glOption as $k => $v) {
                        $att[]   = $k;
                        $att[]   = $v;
                        $arr[$k] = implode(",", $att);
                        $att     = array();
                        $gl      = implode("&", $arr);
                        $arr     = array();
                    }
                }
                if (!empty($gl)) {
                    $ques['relation'] = $gl;
                    $gl               = "";
                } else {
                    $ques['relation'] = '';
                }
            }

            if (empty($customInfo)) {
                $customInfo = array();
            }
            $resultData = [
                'activity_info' => $activityInfo,
                'music_info'    => $musicInfo,
                'custom_info'   => $customInfo,
                'cdn_url'       => full_url($cdnUrl),
                'client'        => $client,
                'list'          => $list,
                'total'         => $total,
            ];

            if ($status == 1) {
                $this->error("活动未发布！", $resultData);
            } else if ($status == 3) {
                $this->error("活动已结束！", $resultData);
            } else if ($status == 4) {
                $this->error("活动已关闭！", $resultData);
            } else if ($startTime > $time) {
                $this->error("活动未开始！", $resultData);
            } else if ($endTime < $time) {
                $this->error("活动已结束！", $resultData);
            }
            $this->success('', $resultData);
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            $this->error("活动异常！");
        }
    }

    /**
     * 登录
     * @return void
     */
    public function login()
    {
        $param      = $this->request->param();
        $activityId = $param['activity_id'] ?? 0; // 活动ID
        $source     = getSource();
        $client     = checkMobile();
        if ($this->request->isGet()) {
            if ($source === 'xcx') {
                $xcxConfig = get_sys_config("", 'xcx_config');
                $isSwitch  = $xcxConfig['is_switch'] ?? 0; // 骗审开关
                if ($isSwitch == 1) {
                    $activityId = $xcxConfig['activity_id'] ?? 0;
                }
                if (empty($activityId)) {
                    $this->error("请通过扫小程序码参加活动！");
                }
            }
        }
        if (empty($activityId)) {
            $this->error("活动异常！");
        }
        $pass = "";
        // 查询活动信息
        $activityModel = new ActivityModel();
        try {
            $activityInfo = $activityModel
                ->field("id,name,status,start_time,end_time,pc_tpl_id,android_tpl_id,password")
                ->where("id", $activityId)
                ->find();
            if (empty($activityInfo)) {
                $this->error("活动不存在！");
            }
            $time         = time();
            $status       = $activityInfo->status ?? 0; // 活动状态
            $startTime    = $activityInfo->start_time ?? 0; // 活动开始时间
            $endTime      = $activityInfo->end_time ?? 0; // 活动结束时间
            $pcTplId      = $activityInfo->pc_tpl_id ?? 0; // pc端模板ID
            $androidTplId = $activityInfo->android_tpl_id ?? 0; // 手机端模板ID
            $pass         = $activityInfo->password ?? ''; // 活动密码

            $pcBgTpl     = "";
            $mobileBgTpl = "";
            // 查询背景模板
            if (!empty($pcTplId) || !empty($androidTplId)) {
                $bgTplModel = new ActivityBgTplModel();
                if (!empty($pcTplId)) {
                    $bgTplInfo = $bgTplModel->field("img")->find($pcTplId);
                    $pcBgTpl   = $bgTplInfo->img ?? '';
                }
                if (!empty($androidTplId)) {
                    $bgTplInfo   = $bgTplModel->field("img")->find($androidTplId);
                    $mobileBgTpl = $bgTplInfo->img ?? '';
                }
            }
            $activityInfo['pc_bg_tpl']     = $pcBgTpl;
            $activityInfo['mobile_bg_tpl'] = $mobileBgTpl;

            $customModel = new CustomModel();
            $musicInfo   = array();
            // 查询自定义配置
            $customInfo = $customModel->field("music_id,onlywx")->where("activity_id", $activityId)->find();
            $musicId    = $customInfo->music_id ?? 0; // 背景音乐ID
            $onlywx     = $customInfo->onlywx ?? 2;
            if (!empty($musicId)) {
                $musicInfo = (new ActivityBgMusicTpl)->field("file_url")->find($musicId);
            }

            if ($onlywx == 1 && $source !== 'xcx' && $source !== 'wechat') {
                $this->error("请通过微信客户端登入！");
            }
            $cdnUrl     = get_cdn_url();
            $resultData = [
                'activity_info' => $activityInfo,
                'music_info'    => $musicInfo,
                'cdn_url'       => full_url($cdnUrl),
                'client'        => $client,
            ];
            if ($status == 1) {
                $this->error("活动未发布！", $resultData);
            } else if ($status == 3) {
                $this->error("活动已结束！", $resultData);
            } else if ($status == 4) {
                $this->error("活动已关闭！", $resultData);
            } else if ($startTime > $time) {
                $this->error("活动未开始！", $resultData);
            } else if ($endTime < $time) {
                $this->error("活动已结束！", $resultData);
            }
            $this->success('', $resultData);
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            $this->error("活动异常！");
        }

        if ($this->request->isPost()) {
            $param    = $this->request->post();
            $password = $param['password'] ?? ''; // 活动密码
            if (empty($pass)) {
                $this->success("登录成功！");
            }
            if (empty($password)) {
                $this->error("请输入活动密码！");
            }
            if ($password !== $pass) {
                $this->error("密码错误！");
            }
            $this->success("登录成功！");
        }
    }

    /**
     * 发送短信验证码
     * @return void
     */
    public function sendCode()
    {
        if ($this->request->isPost()) {
            $param      = $this->request->post();
            $mobile     = $param['mobile'] ?? ''; // 手机号
            $activityId = $param['activity_id'] ?? 0; // 活动ID
            if (empty($mobile)) {
                $this->error("手机号不能为空！");
            }
            $templateCode = get_sys_config("template_code");
            $code         = mt_rand(100000, 999999);
            $msg          = '';
            $content      = json_encode(['code' => $code]);
            $res          = AliYunSms::sendSms($mobile, $content, $templateCode, $activityId, $msg);
            if (!$res) {
                $this->error($msg);
            }
            $this->success("发送成功！");
        }
        $this->error("请求异常！");
    }

    /**
     * 提交问卷
     * @return void
     */
    public function submitData()
    {
        if ($this->request->isPost()) {
            $param = $this->request->post();
            if (empty($param)) {
                $this->error("提交异常！", '');
            }
            $activityId    = $param['activity_id'] ?? 0; // 活动ID
            $quesIdArr     = $param['qid'] ?? []; // 题目ID
            $quesTypeArr   = $param['type'] ?? []; // 题目类型
            $answerArr     = $param['answer'] ?? []; // 答案内容
            $fillBlanksArr = $param['fill_blanks'] ?? []; // 填空内容
            $codeArr       = $param['code'] ?? []; // 短信验证码
            $fileName      = $param['file_name'] ?? []; // 文件名
            $flag          = $param['flag'] ?? ''; // 判断是否绿星计划
            $fileNames     = '';
            $ip            = getClientIp();
            $userId        = $this->auth->id ?? 0; // 用户ID
            $source        = getSource();
            $channel       = 1;
            $startDate     = strtotime(date("Y-m-d", time())); // 开始时间戳
            $endDate       = strtotime(date("Y-m-d 23:59:59", time())); // 结束时间戳
            $jumpUrl       = '';
            if ($source === 'xcx') {
                $channel = 3;
            } else if ($source === 'wechat') {
                $channel = 4;
            } else if (checkMobile()) {
                $channel = 2;
            }
            if (empty($activityId) || ($flag === 'program' && empty($userId))) {
                $this->error("活动异常！", '');
            }
            if (empty($quesIdArr) || empty($quesTypeArr)) {
                $this->error("提交异常！", '');
            }
            // 查询活动信息
            $activityModel        = new ActivityModel();
            $questionsModel       = new Questions();
            $answerSheetModel     = new AnswerSheet();
            $customModel          = new CustomModel();
            $answerModel          = new Answer();
            $answerSheetDataModel = new AnswerSheetData();
            $result               = false;
            Db::startTrans(); // 开启事务
            try {
                $activityInfo = $activityModel
                    ->field("id,status,start_time,end_time,activity_type_id,
                    activity_class_id,project_id,jump_type,jump_url")
                    ->where("id", $activityId)
                    ->find();
                if (empty($activityInfo)) {
                    $this->error("活动不存在！", '');
                }
                $time            = time();
                $status          = $activityInfo->status ?? 0; // 活动状态
                $startTime       = $activityInfo->start_time ?? 0; // 活动开始时间
                $endTime         = $activityInfo->end_time ?? 0; // 活动结束时间
                $activityTypeId  = $activityInfo->activity_type_id ?? 0; // 活动类型ID
                $activityClassId = $activityInfo->activity_class_id ?? 0; // 活动分类ID
                $projectId       = $activityInfo->project_id ?? 0; // 项目ID
                if ($status == 1) {
                    $this->error("活动未发布！", '');
                } else if ($status == 3) {
                    $this->error("活动已结束！", '');
                } else if ($status == 4) {
                    $this->error("活动已关闭！", '');
                } else if ($startTime > $time) {
                    $this->error("活动未开始！", '');
                } else if ($endTime < $time) {
                    $this->error("活动已结束！", '');
                }
                $customInfo = $customModel
                    ->where("activity_id", $activityId)
                    ->find();
                $closewx    = $customInfo->closewx ?? 2; // 是否禁用微信端:(1、禁用2、启用)
                $onlywx     = $customInfo->onlywx ?? 2; // 单独使用微信端:(1、是2、否)
                $score      = $customInfo->score ?? 0; // 活动得分
                if ($onlywx == 1 && $source !== 'xcx' && $source !== 'wechat') {
                    $this->error("请通过微信客户端登入！");
                }

                $tjNum = $customInfo->tj_num ?? 1; // 活动参与人数
                if (empty($tjNum)) {
                    $tjNum = 1;
                }
                $partakeType = $customInfo->partake_type ?? 0; // 限制类型:(1、按总次数2、按每天)
                $dailyNum    = $customInfo->daily_num ?? 0; // 当天参与次数
                $maxSwitch   = $customInfo->max ?? 2; // 回收答卷上限开关
                $maxNum      = $customInfo->max_num ?? 0; // 回收答卷上限数量
                $redbag      = $customInfo->redbag ?? 2; // 是否启用抽奖(1、是2、否)
                $where       = array();
                $where[]     = ['activity_id', '=', $activityId];
                if ($partakeType == 2) {
                    $where[] = ['create_time', '>=', $startDate];
                    $where[] = ['create_time', '<=', $endDate];
                }
                if ($closewx == 2 && ($source === 'wechat' || $source === 'xcx')) {
                    $where[] = ['user_id', '=', $userId];
                    if (empty($userId)) {
                        $this->error("请使用完整服务后提交！");
                    }
                } else if (!empty($userId)) {
                    $where[] = ['user_id', '=', $userId];
                } else {
                    $where[] = ['ip', '=', $ip];
                }
                // 参与人数
                $cyrsCount = $answerSheetModel
                    ->where($where)
                    ->count();
                if ($partakeType == 1 && $cyrsCount >= $tjNum && $tjNum == 1) {
                    $this->error("您已经参与过本次活动了！");
                } else if ($partakeType == 1 && $cyrsCount >= $tjNum) {
                    $this->error("参加活动的次数已达上限！");
                } else if ($partakeType == 2 && $cyrsCount >= $dailyNum) {
                    $this->error("当天参与次数已达上限！");
                } else if ($maxSwitch == 1) {
                    $cyrsTotal = $answerSheetModel
                        ->where('activity_id', $activityId)
                        ->count();
                    if (!empty($maxNum) && $cyrsTotal >= $maxNum && $maxNum > 0) {
                        $this->error("当前问卷已达最大参与人数！");
                    }
                }
                // 查询活动下面的所有题目
                $questionsList = $questionsModel
                    ->field("id,type,title,beiyong,limit")
                    ->where("activity_id", $activityId)
                    ->select()
                    ->toArray();
                $questionsMap  = array();
                // 状态码
                // 1、正常2、验证码不能为空3、验证码错误4、验证码已过期5、只能为数字类型6、超过字数限制
                $statusCode = 1;
                $index      = '';
                foreach ($questionsList as $ques) {
                    $quesId = $ques['id'] ?? 0;
                    if (empty($quesId)) {
                        continue;
                    }
                    $questionsMap[$quesId] = $ques;
                }
                // 查询活动下面的所有选项
                $answerList = $answerModel
                    ->field("id,answer,fill_blanks")
                    ->where("activity_id", $activityId)
                    ->select()
                    ->toArray();
                $answerMap  = array();
                foreach ($answerList as $item) {
                    $answerId = $item['id'] ?? 0;
                    if (empty($answerId)) {
                        continue;
                    }
                    $answerMap[$answerId] = $item;
                }
                unset($questionsList);
                unset($answerList);

                // 插入答卷表
                $sheetData = array(
                    'activity_id' => $activityId,
                    'user_id'     => $userId,
                    'channel'     => $channel,
                    'ip'          => $ip,
                    'project_id'  => $projectId,
                );
                $answerSheetModel->save($sheetData);
                $sheetId      = $answerSheetModel->id; // 答卷ID
                $sheetAddData = array(); // 批量插入答卷数据
                $max_string   = 0;
                foreach ($quesIdArr as $key => $val) {
                    $type  = $quesTypeArr[$key] ?? ''; // 类型
                    $index = $key;
                    if (isEmpty($type)) {
                        continue;
                    }
                    $questionsId = $val; // 题目ID
                    if (!isset($questionsMap[$questionsId])) {
                        continue;
                    }
                    $questionsTitle = $questionsMap[$questionsId]['title'] ?? ''; // 题目标题
                    $questionsType  = $questionsMap[$questionsId]['type'] ?? ''; // 题目类型
                    $beiYong        = $questionsMap[$questionsId]['beiyong'] ?? 2;
                    $limit          = $questionsMap[$questionsId]['limit'] ?? ''; // 限制类型和字数
                    $answerId       = ''; // 选项ID
                    $answerContent  = $answerArr[$key] ?? ''; // 选项内容
                    if ($questionsType == 8) {
                        continue;
                    }
                    if (in_array($type, [0, 1, 6, 7, 17, 18])) {
                        $answerId = $answerArr[$key] ?? 0;
                        if (is_array($answerId)) {
                            $aContent = '';
                            foreach ($answerId as $aid) {
                                if (!isset($answerMap[$aid])) {
                                    continue;
                                }
                                $answerInfo = $answerMap[$aid];
                                if (!empty($aContent)) {
                                    $aContent .= ",";
                                }
                                $aContent   .= $answerInfo['answer'] ?? '';
                                $fillBlanks = $answerInfo['fill_blanks'] ?? 2;
                                if ($fillBlanks == 1 && isset($fillBlanksArr[$key])) {
                                    $aContent .= ": " . $fillBlanksArr[$key] ?? '';
                                }
                            }
                            $answerContent = $aContent;
                            $answerId      = implode(",", $answerId);
                        } else {
                            $answerContent = $answerMap[$answerId]['answer'] ?? ''; // 选项内容
                        }
                    } else if ($type == 2) {
                        if (!empty($limit)) {
                            $arr        = explode(",", $limit);
                            $limitType  = $arr[0];
                            $max_string = $arr[1];
                            if ($limitType == 1 && !is_numeric($answerContent) && !empty($answerContent)) {
                                $statusCode = 5;
                                break;
                            } else if ($max_string > 0 && mb_strlen($answerContent) > $max_string) {
                                $statusCode = 6;
                                break;
                            }
                        }
                    } else if ($type == 4) {
                        if (is_array($answerContent)) {
                            $answerContent = implode(",", $answerContent);
                        }
                        $fileName = $fileName[$key] ?? [];
                        if (is_array($fileName)) {
                            $fileNames = implode(",", $fileName);
                        } else {
                            $fileNames = $fileName;
                        }
                    } else if ($type == 11 || $type == 12 || $type == 13) {
                        if (is_array($answerContent)) {
                            $answerContent = implode(",", $answerContent);
                        }
                    } else if ($type == 14) {
                        $mobile = $answerContent;
                        // 手机号短信验证
                        if ($beiYong == 1) {
                            $code = $codeArr[$key];
                            if (empty($code)) {
                                $statusCode = 2;
                                break;
                            }
                            $smsWhere   = array();
                            $smsWhere[] = ['type', '=', 1];
                            $smsWhere[] = ['code', '=', $code];
                            $smsWhere[] = ['mobile', '=', $mobile];
                            $smsRecord  = (new SmsRecord())
                                ->field("id,expire_time")
                                ->where($smsWhere)
                                ->order("id", 'desc')
                                ->find();
                            if (empty($smsRecord)) {
                                $statusCode = 3;
                                break;
                            }
                            $expireTime = $smsRecord->expire_time ?? 0; // 有效期
                            if ($expireTime < time()) {
                                $statusCode = 4;
                                break;
                            }
                        }
                    } else {
                        if (isset($answerArr[$key])) {
                            $answerContent = $answerArr[$key] ?? '';
                        }
                    }
                    $sheetAddData[] = [
                        'activity_id'     => $activityId,
                        'user_id'         => $userId,
                        'questions_id'    => $questionsId,
                        'questions_title' => $questionsTitle,
                        'questions_type'  => $questionsType,
                        'answer_id'       => $answerId,
                        'answer_content'  => $answerContent,
                        'file_name'       => $fileNames,
                        'sheet_id'        => $sheetId
                    ];
                }
                if ($statusCode == 2) {
                    $this->error("验证码不能为空！", ['index' => $index], -1);
                } else if ($statusCode == 3) {
                    $this->error("验证码错误！", ['index' => $index], -1);
                } else if ($statusCode == 4) {
                    $this->error("验证码已过期！", ['index' => $index], -1);
                } else if ($statusCode == 5) {
                    $this->error("只能输入数字！", ['index' => $index], -1);
                } else if ($statusCode == 6) {
                    $this->error("输入的字符不可超过" . $max_string . "个", ['index' => $index], -1);
                }
                try {
                    $answerSheetDataModel->saveAll($sheetAddData);
                } catch (Exception $e) {
                    $this->error("提交异常！", '');
                }
                // 保存绿星计划数据
                if ($flag === 'program') {
                    // 查询用户是否已绑定机构
                    $where      = array();
                    $where[]    = ['user_id', '=', $userId];
                    $oUserModel = new OrganizeUserModel();
                    $oUserInfo  = $oUserModel->field("organize_id")
                        ->where($where)
                        ->find();
                    if (empty($oUserInfo)) {
                        $this->error("用户不存在！", $userId, 2);
                    }
                    $organizeId = $oUserInfo->organize_id ?? 0; // 机构ID
                    if (empty($organizeId)) {
                        $this->error("请先绑定组织机构！", $userId, 2);
                    }
                    $data         = [
                        'activity_id'       => $activityId,
                        'user_id'           => $userId,
                        'organize_id'       => $organizeId,
                        'activity_type_id'  => $activityTypeId,
                        'activity_class_id' => $activityClassId,
                        'project_id'        => $projectId,
                        'sheet_id'          => $sheetId,
                    ];
                    $pRecordModel = new ProgramRecord();
                    $pRecordModel->save($data);

                    // 用户积分变动
                    $userSRModel = new UserScoreRecord();
                    $data        = array(
                        'activity_id'       => $activityId,
                        'user_id'           => $userId,
                        'organize_id'       => $organizeId,
                        'activity_type_id'  => $activityTypeId,
                        'activity_class_id' => $activityClassId,
                        'project_id'        => $projectId,
                        'score'             => $score,
                        'source'            => 1,
                    );
                    $userSRModel->save($data);
                }
                $result = true;
                // 查询抽奖记录
                if ($redbag == 1) {
                    // 查询抽奖次数
                    if (!empty($userId)) {
                        $prizeRecord = (new PrizeRecord())
                            ->where("user_id", $userId)
                            ->find();
                    }
                    if (empty($userId) || empty($prizeRecord)) {
                        $jumpUrl = '../activity/prize.html?activity_id=' . $activityId . '&sheet_id=' . $sheetId;
                    }
                }

                if (empty($jumpUrl)) {
                    if ($activityInfo->jump_type == '2') {
                        if (!empty($activityInfo->jump_url)) {
                            $jumpUrl = $activityInfo->jump_url;
                        }
                    }
                }
                if(empty($jumpUrl)){
                    $jumpUrl = '../activity/zdypage.html?activity_id=' . $activityId;
                }
                Db::commit(); // 提交事务
            } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
                Db::rollback(); // 回滚
                $this->error("活动异常！", '');
            }
            if ($result) {
                $this->success("提交成功！", ['url' => $jumpUrl]);
            } else {
                $this->error("提交失败！", '');
            }
        }
        $this->error("请求异常！", '');
    }

    /**
     * 自定义欢迎页
     * @return void
     */
    public function zdyPage()
    {
        if ($this->request->isGet()) {
            $param = $this->request->get();
            if (empty($param)) {
                $this->error("提交异常！", '');
            }
            $activityModel = new ActivityModel();
            $activityId    = $param['activity_id'] ?? 0; // 活动ID
            $client        = checkMobile();
            try {
                $activityInfo = $activityModel
                    ->field("id,name,jump_content,pc_tpl_id,android_tpl_id")
                    ->where("id", $activityId)
                    ->find();
                if (empty($activityInfo)) {
                    $activityInfo = array();
                } else {
                    $pcTplId                       = $activityInfo->pc_tpl_id ?? 0; // pc端模板ID
                    $androidTplId                  = $activityInfo->android_tpl_id ?? 0; // 手机端模板ID
                    $activityInfo['pc_bg_tpl']     = "";
                    $activityInfo['mobile_bg_tpl'] = "";
                    // 查询背景模板
                    if (!empty($pcTplId) || !empty($androidTplId)) {
                        $bgTplModel = new ActivityBgTplModel();
                        if (!empty($pcTplId)) {
                            $bgTplInfo                 = $bgTplModel->field("img")->find($pcTplId);
                            $activityInfo['pc_bg_tpl'] = $bgTplInfo->img ?? '';
                        }
                        if (!empty($androidTplId)) {
                            $bgTplInfo                     = $bgTplModel->field("img")->find($androidTplId);
                            $activityInfo['mobile_bg_tpl'] = $bgTplInfo->img ?? '';
                        }
                    }
                }
            } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
                $activityInfo = array();
            }
            $this->success("", ['info' => $activityInfo, 'client' => $client]);
        }
        $this->error("请求异常！");
    }

    /**
     * 获取微信分享
     * @return void
     */
    public function getWeChatShare()
    {
        if ($this->request->isGet()) {
            $param      = $this->request->get();
            $activityId = $param['activity_id'] ?? 0; // 活动ID
            $flag       = $param['flag'] ?? ''; // 标识
            $webUrl     = '';
            if (isset($_SERVER)) {
                $webUrl = $_SERVER['HTTP_REFERER'] ?? ''; // 网页URL不带#
            }
            $params         = getWeChatShare($webUrl);
            $url            = getJumpUrl($webUrl, ['token']);
            $httpHost       = getHttp() . '://' . $_SERVER['HTTP_HOST'] ?? '';
            $noShareUrlList = $this->getNoShareUrl();
            foreach ($noShareUrlList as $item) {
                if (stristr($webUrl, $item)) {
                    $path = "";
                    if (stristr($webUrl, '/addons/')) {
                        $path = "/addons/jueqi_survey_pro/public";
                    }
                    if (stristr($webUrl, '/frontend/view/')) {
                        $url = $httpHost . $path . '/frontend/view/activity/index.html?activity_id=' . $activityId . '&flag=' . $flag;
                    } else {
                        $url = $httpHost . $path . '/program/view/program/index.html';
                    }
                    break;
                }
            }
            $params['url']    = $url;
            $params['title']  = '';
            $params['desc']   = '';
            $params['imgUrl'] = '';
            // 查询分享配置
            $shareModel = new Share();
            try {
                if (stristr($webUrl, '/frontend/view/')) {
                    $shareInfo        = $shareModel->where('activity_id', $activityId)->find();
                    $params['title']  = $shareInfo->title ?? '';
                    $params['desc']   = $shareInfo->content ?? '';
                    $params['imgUrl'] = $shareInfo->img ?? '';
                } else {
                    $shareInfo        = get_sys_config('', 'share');
                    $params['title']  = $shareInfo['share_title'] ?? '';
                    $params['desc']   = $shareInfo['share_content'] ?? '';
                    $params['imgUrl'] = $shareInfo['share_img'] ?? '';
                }
                $this->success("", $params);
            } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
                $this->success("", $params);
            }
        }
        $this->error("请求异常！");
    }

    /**
     * 不能分享的url
     * @return array
     */
    public function getNoShareUrl(): array
    {
        return [
            'program/view/program/bind',
            'program/view/program/activity_list',
            'program/view/program/collect',
            'frontend/view/activity/prize',
            'frontend/view/activity/zdypage',
        ];
    }

    /**
     * 获取小程序骗审活动ID
     * @return void
     */
    public function getXcxConfig()
    {
        $xcxConfig  = get_sys_config("", 'xcx_config');
        $activityId = $xcxConfig['activity_id'] ?? 0;
        $isSwitch   = $xcxConfig['is_switch'] ?? 2;
        if ($isSwitch == 2) {
            $activityId = 0;
        }
        $this->success("", ['activity_id' => $activityId]);
    }

}
